package com.gxa.hualianeshop.interceptor;

import com.gxa.hualianeshop.entity.vo.UserVO;
import com.gxa.hualianeshop.threadLocal.UserThreadLocal;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bill
 * @date 2023/7/10 16:23
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 拦截用户携带的请求头
        String token = request.getHeader("token");

        // 向SSO服务器发起远程调用
        String url = "http://localhost:9000/user/getUserVOByToken";

        //准备参数

        //发起调用
        RestTemplate restTemplate = new RestTemplate();
        UserVO userVO = restTemplate.postForObject(url, null, UserVO.class);

        // 通过ThreadLocal
        UserThreadLocal.set(userVO);


        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在拦截器的后置处理: 销毁线程作用域中的内容
        UserThreadLocal.remove();
    }
}
